package com.hxzy.projectssmplus.security.filter;

import com.hxzy.projectssmplus.security.LoginUserDetails;
import com.hxzy.projectssmplus.security.SecurityUtils;
import com.hxzy.projectssmplus.security.TokenService;
import com.hxzy.projectssmplus.util.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性  filter
 *
 * @author admin
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        //如果uuid在redis中存在
        LoginUserDetails loginUser = tokenService.getLoginUserDetails(request);

        //spring security基于session认证的，前后端分离，你每一次的session存储值，都认为没有登陆成功过.
        //处理来处理 spring security，让他认为我们是登录成功过的
        if ( loginUser!=null &&  SecurityUtils.getAuthentication()==null)
        {
            //为uuid判断它的过期时间是否<15分钟，如果是重新为它分配时间
            tokenService.verifyToken(loginUser);

            //模拟登录成功
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }


        //放行
        chain.doFilter(request, response);
    }
}
